'''
Created on Jun 15, 2011

@author: oabalbin
'''

import os
from collections import defaultdict, deque


def myddict(): 
    return defaultdict(deque)
  
def nested_ddict(): 
    return defaultdict(myddict)

def check_create_dir(root_path, dir_name=None):
    if not os.path.isdir(root_path):
            os.mkdir( root_path )
    if dir_name is not None:
        subfolder=os.path.join(root_path,dir_name)
        if not os.path.isdir(subfolder):
                os.mkdir( subfolder )
    else:             
        subfolder=root_path

    return subfolder


def define_patients_cohort(analysis,use_recal_files):
    '''
    Define a patient and samples that correspond to that patient.
    Divide patient samples into benign and tumor samples
    '''
    cohort_patients = nested_ddict()
    for sp in analysis.samples:
        
        if use_recal_files:
            analysis.sam_tools_files(use_recal_files)
            for sp in analysis.samples:
                
                if sp.category=='benign':
                    cohort_patients[sp.patient_id]['benign'].append(sp.sorted_mmarkdup_bam)
                else:
                    cohort_patients[sp.patient_id]['tumor'].append(sp.sorted_mmarkdup_bam)
        else:
            analysis.sam_tools_files(use_recal_files)
            for sp in analysis.samples:
                if sp.category=='benign':
                    cohort_patients[sp.patient_id]['benign'].append(sp.sorted_quickmmdup_bam)
                else:
                    cohort_patients[sp.patient_id]['tumor'].append(sp.sorted_quickmmdup_bam)

    return cohort_patients


def define_sample_cohort(analysis,use_recal_files):
    '''
    Define a patient and samples that correspond to that patient.
    Divide patient samples into benign and tumor samples
    '''
    cohort_samples = defaultdict(deque)
    
    if use_recal_files:
        analysis.sam_tools_files(use_recal_files)
        for sp in analysis.samples:
            if sp.category=='benign':
                cohort_samples['benign'].append(sp.sorted_mmarkdup_bam)
            else:
                cohort_samples['tumor'].append(sp.sorted_mmarkdup_bam)
    else:
        analysis.sam_tools_files(use_recal_files)
        for sp in analysis.samples:
            if sp.category=='benign':
                cohort_samples['benign'].append(sp.sorted_quickmmdup_bam)
            else:
                cohort_samples['tumor'].append(sp.sorted_quickmmdup_bam)
    
    return cohort_samples
